<script setup>
import { ref, inject, onMounted } from "vue";
import { useRouter } from "vue-router";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";

const axios = inject("axios");

const page = ref(1);
const pageSize = ref(10);
const lastSearchText = ref("");

onMounted(() => {
  fetchArticleData();
  fetchTagsData();
});

const fetchArticleData = async () => {
  try {
    const res = await axios.get(`/articles`, {
      params: {
        page: page.value,
        pageSize: pageSize.value,
      },
    });
    articleList.value = res.data.data.record;

    articleList.value = res.data.data.record;

    console.log(articleList.value);
    console.log(res.data);
  } catch (error) {
    ElMessage.error("网络错误", error);
  }
};

const fetchArticleByTagId = async (tagId) => {
  try {
    // 请求固定的文章
    const res = await axios.get(`/tag/${tagId}/articles`, {
      params: {
        page: page.value,
        pageSize: pageSize.value,
      },
    });
    articleList.value = res.data.data.record;
  } catch {
    ElMessage.error("网络错误");
  }
};

const fetchTagsData = async () => {
  try {
    const res = await axios.get(`/tagList`);
    if (res.data.code === 200) {
      tagList.value = [...tagList.value, ...res.data.data.record];
      // console.log("标签查询结果", res.data.data);
      console.log(tagList.value);
    } else {
      ElMessage.error("获取标签数据失败", res.data.message);
    }
  } catch (error) {
    ElMessage.error("网络错误", error);
  }
};

const fetchArticleDataBySearch = async (searchText) => {
  try {
    const res = await axios.get(`/articles/search`, {
      params: {
        title: searchText,
        page: 1,
        pageSize: 10,
      },
    });

    console.log("搜索结果", res.data);

    articleList.value = res.data.data.record;

    if (res.data.code === 200) {
      ElMessage.success("请求成功");
    } else {
      ElMessage.error("请求失败");
    }
  } catch {
    ElMessage.error("网络错误");
  }
};

const router = useRouter();
const tagList = ref([
  {
    tagId: 0,
    tagName: "全部",
    describe: "所有的文章",
  },
]);

const articleList = ref([]);

const activeTagId = ref(0);

const searchText = ref("");

const handleClick = (articleId) => {
  router.push(`/article/${articleId}`);
};

const handleChangeTabs = (pane) => {
  // pane.props.name 就是当前点击的 name
  if (activeTagId.value != pane.props.name) {
    activeTagId.value = pane.props.name;
    console.log("当前选中的 tab:", pane.props.name);
    if (activeTagId.value === 0) {
      fetchArticleData();
      return;
    }
    fetchArticleByTagId(activeTagId.value);
  }
};

const handleSearchArticle = async () => {
  console.log("搜索文章", searchText.value);
  if (!searchText.value && lastSearchText.value != searchText.value) {
    fetchArticleData();
  } else if (searchText.value) {
    fetchArticleDataBySearch(searchText.value);
  } else {
    ElMessage.error("请输入搜索内容");
    return;
  }
  lastSearchText.value = searchText.value;
};
</script>

<template>
  <div class="header-search">
    <el-input
      v-model="searchText"
      placeholder="搜索文章"
      size="large"
      :prefix-icon="Search"
      clearable
    />
    <el-button plain size="large" @click="handleSearchArticle">搜索</el-button>
  </div>
  <div class="home-page">
    <div class="tag-list">
      <el-tabs v-model="activeTagId" @tab-click="handleChangeTabs">
        <el-tab-pane
          v-for="tag in tagList"
          :key="tag.tagId"
          :label="tag.tagName"
          :name="tag.tagId"
        >
        </el-tab-pane>
      </el-tabs>
    </div>
    <div v-if="!articleList.length">
      <el-result
        icon="primary"
        title="该标签下暂无文章"
        sub-title="尝试换一个标签再试试吧"
      >
      </el-result>
    </div>
    <div class="article-list" v-else>
      <div class="articles">
        <div
          v-for="article in articleList"
          :key="article.articleId"
          class="article-card"
          @click="handleClick(article.articleId)"
        >
          <h3>{{ article.title }}</h3>
          <p class="summary">
            {{ article.describe || "该作者似乎有点懒，暂无简述" }}
          </p>
          <div class="article-meta">
            <span
              >发布时间：{{
                dayjs(article.createdAt).format("YYYY年MM月DD日 HH:mm")
              }}</span
            >
            <span
              >更新时间：{{
                dayjs(article.updatedAt).format("YYYY年MM月DD日 HH:mm")
              }}</span
            >
            <span>作者: {{ article.author }}</span>
          </div>
          <!-- <router-link `" class="read-more"
            >阅读更多</router-link
          > -->
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.home-page {
  width: 100%;
  max-width: 1200px;
  margin: 80px auto 0;
  padding: 0 20px;
}
.header-search {
  width: 300px;
  position: absolute;
  left: 41%;
  top: 5%;
  display: flex;
}

.banner h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  color: #333;
}

.banner p {
  font-size: 1.2rem;
  color: #666;
}

.article-list h2 {
  font-size: 1.8rem;
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
}

.articles {
  display: flex;
  gap: 20px;
  flex-direction: column;
  align-items: stretch;
}

.article-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
  transition: transform 0.3s ease;
}

.article-card:hover {
  transform: translateY(-5px);
  cursor: pointer;
}

.article-card h3 {
  font-size: 1.3rem;
  margin-bottom: 10px;
  color: #333;
}

.summary {
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  color: #888;
  font-size: 0.9rem;
  margin-bottom: 15px;
}

.read-more {
  display: inline-block;
  color: #646cff;
  font-weight: 500;
}
</style>
